/**
 * Created by moko1988
 * 2016年01月16日16:10:34
 */
define([
    'backbone',
    'models/numberManage/list',
    'text!templets/numberManage/list.htm',
    'text!templets/numberManage/list-modal-add.htm',
    'text!templets/numberManage/list-modal-change.htm',
    'text!templets/numberManage/list-model-reChange.htm',
    'utils/dataTableUtil',
    'uploadify',
    'utils/urlUtil',
    'jquerypage',
    'select2'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    ModalChange,
    ModalReChange,
    DataTable
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun',
            'click [role=edit]': 'editFun',
            'click [role=save]': 'saveFun',
            'click [role=saveChange]': 'saveChange',
            'click [role=saveReChange]': 'saveReChange',
            'click [role=del]': 'delFun',
            'click [role=rank]': 'rank',
            'click [role=improve]': 'improve',  //完善信息
            'click [role=hotRank]': 'hotRank',  //热门排序
            'click #checkAll': 'checkAll', 
            'click input[name=idarr]': 'checkItem',
            'change #category': 'changeListCategory_ad',
            'click [role=search]': 'searchCharge'//查询
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.idArr = [];
            $('#pageSize').select2();
            // this.render();
            this.renderCategory_type();
        },
         renderCategory_type: function(){
            var _this = this;
            Model.fetchCategory_type({
                type: 'get',
                success: function(map) {
                    // console.log(map);
                    var opts = '<option value="">选择分类</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.type_id] = o;
                        opts += '<option value="'+o.type_id+'">'+ o.type_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#category').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })
        },

        changeListCategory_ad: function(e){
            var $target = $(e.currentTarget);
            this.params["channel"] = $target.val();  
        },

        params:{
            channel:""
        },

        searchCharge: function(e){
            var _this = this;
            Model.search({
                data: {
                    type_id:  _this.params["channel"],
                    page: this.page,
                    page_size: this.listRows
                },
                success: function(map) {
                    console.log(map)
                    var data = map.list,
                        page = map.page,
                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.public_id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.public_id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if (i == 0) {

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {

                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }

                        o.rank = rank_up + rank_down;

                        var btn_edit = '<button class="btn" role="edit" data-id="' + o.public_id+ '" >修改</button>',
                            btn_del = '<button class="btn" role="del" data-id="' + o.public_id+ '" >删除</button>';
                        o.btns = btn_edit + btn_del;
                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">','序号', '所属公司', '所属分类', '公众号名称', '公众号',  '发布(次/篇)', '头条阅读数','平均阅读数','总点赞数', '影响力', '精选', '排序', '操作'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'public_id'),
                            _.pluck(data,'corporate_name'),
                            _.pluck(data,'type_name'),
                            _.pluck(data,'name'),
                            _.pluck(data,'public'),
                            _.pluck(data,'pian'),
                            _.pluck(data,'first_num'),
                            _.pluck(data,'average_num'),
                            _.pluck(data,'like'),
                            _.pluck(data,'effect'),
                            _.pluck(data,'selected'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );

                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                data: {
                    page: this.page,
                    page_size: this.listRows,
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,
                        count = data.length;
                         _this.pageTotal = page.total_page;

                    _.each(data,function(o, i){

                        o.checkbox = '<input type="checkbox" value="'+ o.public_id +'" name="idarr">';

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.public_id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.public_id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if (i == 0) {

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {

                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }

                        o.rank = rank_up + rank_down;

                        var btn_edit = '<button class="btn" role="edit" data-id="' + o.public_id+ '" >修改</button>',
                            btn_del = '<button class="btn" role="del" data-id="' + o.public_id+ '" >删除</button>';
                        o.btns = btn_edit + btn_del;
                    })

                    var tableHead = ['<input type="checkbox" id="checkAll">','序号', '所属公司', '所属分类', '公众号名称', '公众号',  '发布(次/篇)', '头条阅读数','平均阅读数','总点赞数', '影响力', '精选', '排序', '操作'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'public_id'),
                            _.pluck(data,'corporate_name'),
                            _.pluck(data,'type_name'),
                            _.pluck(data,'name'),
                            _.pluck(data,'public'),
                            _.pluck(data,'pian'),
                            _.pluck(data,'first_num'),
                            _.pluck(data,'average_num'),
                            _.pluck(data,'like'),
                            _.pluck(data,'effect'),
                            _.pluck(data,'selected'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                     $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
         /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },

        //添加
        addFun: function() {
            $(this.el).append(ModalAdd);
            var $myModal = $('#myModal');
            $myModal.find('h4').html('添加公众号');
            $myModal.off();
            $myModal.modal();
            this.uploadifyIni(); //初始化上传按钮
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
                _this = this; 

             Model.fetchCategory_type({
                type: 'get',
                success: function(map) {
                    var opts = '<option value="">选择分类</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.type_id] = o;
                        opts += '<option value="'+o.type_id+'">'+ o.type_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#theCategorys').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            });

             Model.fetchCategory_channel({
                type: 'get',
                success: function(map) {
                    var opts = '<option value="">选择渠道</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.corporate_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#theChannels').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })
        },
        //添加提交
         saveFun: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=save]'),
        
                isOK = this.checkForm();

                 if(isOK){
                    subBtn.prop('disabled', true);
                    Model.insert({
                        type: 'post',
                        data: $form.serialize(),
                        success: function() {
                            subBtn.prop('disabled', false);
                            jAlert('提交成功', function() {
                                $myModal.modal('hide');
                                _this.render();
                            })
                        },
                        error:function(msg){
                            jAlert(msg,function(){
                                subBtn.prop('disabled', false);
                            })
                        }
                    })
              }
        },
     
        /*修改*/
        editFun: function(e){
            $(this.el).append(ModalChange);
            var $target = $(e.currentTarget),
                $myModal = $('#myModal'),
                id = $target.attr('data-id'),
                _this = this;
            $myModal.off();
            $myModal.modal();
            $myModal.find('h4').html('修改公众号信息');
            $myModal.find('[role=save]').prop('disabled', true);
            this.uploadifyIni();
            /*弹窗关闭*/
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
            $('#loading').html(loading);
            $('#data-form').hide();

            Model.fetchCategory_type({
                type: 'get',
                success: function(map) {
                    var opts = '<option value="">选择分类</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.type_id] = o;
                        opts += '<option value="'+o.type_id+'">'+ o.type_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#theCategorys').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            });

             Model.fetchCategory_channel({
                type: 'get',
                success: function(map) {
                    var opts = '<option value="">选择渠道</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.corporate_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#theChannels').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    _this.render();
                }
            })

            Model.fetchInfo({
                data: {
                    public: id
                },
                success: function(map) {

                    $myModal.find('input[name=id]').val(id);
                    $myModal.find('input[name=name]').val(map.name);
                    $myModal.find('input[name=number]').val(map.public);
                    $myModal.find('input[name=label]').val(map.label_name);
                    $myModal.find("input[name=selected][value='"+map.selected+"']").attr('checked','checked');
                    $myModal.find('textarea[name=details]').val(map.details);

                    map.head_pic == '' || _this.imgEcho($myModal.find('input[name=head_pic]'), map.head_pic);
                    map.brand_pic == '' || _this.imgEcho($myModal.find('input[name=brand_pic]'), map.brand_pic);

                   // map.head_pic = _this.imgEcho($myModal.find('input[name=ad_pic]'), map.head_pic);      //头像
                   // map.head_pic=_this.imgEcho($myModal.find('input[name=brand_pic]'), map.brand_pic);   //二维码

                    $('#loading').html('');
                    $('#data-form').show();
                    $myModal.find('[role=save]').prop('disabled', false);
                }
            })
        },

        //提交修改
         saveChange : function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveChange]'),               

                isOK = this.checkForm();

                if(isOK){
                   subBtn.prop('disabled', true);
                   Model.change({
                       type: 'post',
                       data: $form.serialize(),
                       success: function() {
                           subBtn.prop('disabled', false);
                           jAlert('提交成功', function() {
                               $myModal.modal('hide');
                               _this.render();
                           })
                       },
                       error:function(msg){
                           jAlert(msg,function(){
                               subBtn.prop('disabled', false);
                           })
                       }
                   })

               }
                
        },



        // 完善信息
        improve: function(e){
             $(this.el).append(ModalReChange);
            var $target = $(e.currentTarget),
                $myModal = $('#myModal'),
                id = this.idArr[0],
                _this = this;          
             if (this.idArr.length) {   
                $myModal.off();
                $myModal.modal();
                $myModal.find('h4').html('完善信息');
                // $myModal.find('[role=saveReChange]').prop('disabled', true);
                $('#add-category').prop('disabled',false).html(this.categoryOpts);
                /*弹窗关闭*/
                $myModal.on('hidden.bs.modal', function(e) {
                    $myModal.remove();
                });
                $('#loading').html(loading);
                $('#data-form').hide();
                //弹出对话框
                // this.reviewFun();

                Model.fetchMessage({
                    data: {
                        id: id
                    },
                    success: function(map) {
                    $myModal.find('input[name=id]').val(id);
                    $myModal.find('input[name=distribute]').val(map.pian);
                    $myModal.find('input[name=firstRead]').val(map.first_num);
                    $myModal.find('input[name=averageRead]').val(map.average_num);
                    $myModal.find('input[name=allLike]').val(map.like);
                    $myModal.find('textarea[name=influence]').val(map.effect);

                    $('#loading').html('');
                    $('#data-form').show();
                    $myModal.find('[role=save]').prop('disabled', false);
                }
                 });
            } else {
                jAlert('请选择要操作的数据');
            }
        }, 
    
        // 完善信息提交
         saveReChange : function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveReChange]'),               

                isOK = this.checkForm();

                if(isOK){
                   subBtn.prop('disabled', true);
                   Model.reChange({
                       type: 'post',
                       data: $form.serialize(),
                       success: function() {
                           subBtn.prop('disabled', false);
                           jAlert('提交成功', function() {
                               $myModal.modal('hide');
                               _this.render();
                           })
                       },
                       error:function(msg){
                           jAlert(msg,function(){
                               subBtn.prop('disabled', false);
                           })
                       }
                   })

               }        
        },

        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.attr('data-id'),
                _this = this,
                msg = '<p>确定要删除该客户？</p>';
            jConfirm(msg, function(s) {
                if (s) {
                    Model.delete({
                        data: {
                            public: id
                        },
                        success: function(map) {
                            jAlert('删除成功', function() {
                                _this.render();
                            })
                        }
                    })
                }
            })
        },
        rank: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                type:'post',
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*编辑图片回显*/
        imgEcho: function($target, val) {
         
            var $wrap = $target.parent('[role=upimg]'),
                $info = $wrap.find('.file-info'),
                $val = $wrap.find('.file-val');

            $target.val(val);
            $info.addClass('hide');
            $val.removeClass('hide').find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + val);
            $wrap.find('.uploadify').css('z-index', -1);
        },
         /*初始化uploadify上传按钮*/
        uploadifyIni: function() {
            var _this = this;
            $('input[role=file-upload]').each(function() {
                var $this = $(this),
                    $wrap = $this.parents('[role=upimg]'),
                    $fileCanvas = $wrap.find('.file-canvas'),
                    $info = $fileCanvas.find('.file-info'),
                    $loading = $fileCanvas.find('.file-loading'),
                    $val = $fileCanvas.find('.file-val'),
                    $input = $wrap.find('input.file-input'),
                    index = $('[role=upimg]').index($wrap);
                $loading.html(loading2);
                $(this).attr('id', 'file-upload-' + index);
                $this.uploadify({
                    height: 23,
                    width: 43,
                    removeTimeout: 1,
                    buttonText: '上传',
                    fileTypeExts: '*',
                    fileSizeLimit: '4MB', //上传文件大小限制
                    multi: false, //是否可以上传多个文件
                     swf: '/Public/admin/images/uploadify.swf', //上传flash地址（注意路径）
                    uploader: adminPath + '/index/uploadfile', //上传数据处理文件Ajax（注意路径）
                    /*开始上传之前触发*/
                    onUploadStart: function() {
                        $info.addClass('hide');
                        $loading.removeClass('hide');
                        $wrap.find('.uploadify').css('z-index', -1);
                    },
                    /*上传完成之后触发*/
                    onUploadSuccess: function(file, data, response) {
                        if (response) {
                            data = $.parseJSON(data);
                            if (data.code == 1) {
                                $input.val(data.filename);
                                $val.removeClass('hide');
                                $val.find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + data.filename);
                                $loading.addClass('hide');
                            } else {
                                jAlert(data.msg, function() {
                                    $info.removeClass('hide');
                                    $loading.addClass('hide');
                                    $wrap.find('.uploadify').css('z-index', 1);
                                });
                            }
                        }
                    }
                })
                /*鼠标经过上传完的图片隐藏展示删除按钮*/
                $val.hover(function() {
                    $(this).find('i').show();
                }, function() {
                    $(this).find('i').hide();
                });
                /*鼠标经过上传面板隐藏展示上传按钮*/
                $fileCanvas.hover(function() {
                    $(this).find('.uploadify-button ').show();
                }, function() {
                    $(this).find('.uploadify-button ').hide();
                });
                /*点击删除图片按钮*/
                $val.find('i').click(function() {
                    _this.resetfileCanvas($wrap);
                });
            })
        },
        /*还原上传面板*/
        resetfileCanvas: function($wrap) {
            $wrap.find('input.file-input').val('');
            $wrap.find('.file-val').addClass('hide');
            $wrap.find('.file-info').removeClass('hide');
            $wrap.find('.uploadify').css('z-index', 1);
        },
        /*初始化uploadify上传按钮(多图上传)*/
        uploadifyMultiIni: function() {
            var _this = this;
            $('#file-upload-multi').uploadify({
                height: 23,
                width: 143,
                buttonText: '上传(支持选择多图)',
                fileTypeExts: '*',
                fileSizeLimit: '4MB', //上传文件大小限制
                multi: true, //是否可以上传多个文件
                swf: ROOT_PATH + '/Public/admin/images/uploadify.swf', //上传flash地址（注意路径）
                uploader: ADMIN_PATH + '/index/uploadfile', //上传数据处理文件Ajax（注意路径）
                /*开始上传之前触发*/
                onUploadStart: function() {
                    if(_this.MultNO >= _this.maxMult){
                        $('#file-upload-multi').uploadify('cancel', '*');//清除剩余的上传队列
                        jAlert('最多只能上传' + _this.maxMult + '张!');
                    }
                },
                /*上传完成之后触发*/
                onUploadSuccess: function(file, data, response) {
                    if (response) {
                        data = $.parseJSON(data);
                        if (data.code == 1) {
                            _this.MultNO++;
                            var imgList = '<div class="img-list">';
                            imgList += '<input role="img-list" type="hidden" value="'+ data.filename +'">';
                            imgList += '<img src="' + PIC_PATH + data.filename + '">';
                            imgList += '<i title="删除"></i>';
                            imgList += '</div>';
                            $('#multi-warp').append(imgList);

                        }
                    }
                }
            })
            /*鼠标经过上传完的图片隐藏展示删除按钮*/
            $('#multi-warp').on('mousemove', '.img-list', function(){
                $(this).find('i').show();
            });
            $('#multi-warp').on('mouseout', '.img-list', function(){
                $(this).find('i').hide();
            });
            /*点击删除图片按钮*/
            $('#multi-warp').on('click','.img-list i', function(){
                var $wrap = $(this).parent();
                $wrap.remove();
                _this.MultNO--;
            })
        },

           /*验证*/
        checkForm: function() {
            var $form = $('[role=form]'),
                $name = $form.find('input[name=name]'),
                $number = $form.find('input[name=number]'),
                $label = $form.find('input[name=label]'),

                //渠道下拉框
                $select1 = $('#theChannels');
                $selOpt1 = $('#theChannels option:selected');

                //分类下拉框
                $select2 = $('#theCategorys');
                $selOpt2 = $('#theCategorys option:selected');

                getTip = function(e) {
                    var text = e.siblings('label.control-label').html();
                    // text = text.substr(0, text.length - 1);
                    return text;
                },
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
                
                //公众号名称
                if ($.trim($name.val()) == '') {
                    errShow($name, '请填写' + getTip($name));
                } 

                //公众号
                if ($.trim($number.val()) == '') {
                    errShow($number, '请填写' + getTip($number));
                } 
                //标签
                if ($.trim($label.val()) == '') {
                    errShow($label, '请填写' + getTip($label));
                } 


                //渠道下拉框
                if ($.trim($selOpt1.val()) == '') {
                     errShow($select1, '请选择渠道');
                } 

                  //分类下拉框
                if ($.trim($selOpt2.val()) == '') {
                     errShow($select2, '请选择分类');
                } 
            return rest;
        },

        
    })
    return view;
})